package com.sitanyun.merchant.guide.view.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.provider.Settings;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.LogUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.sitanyun.merchant.guide.R;
import com.sitanyun.merchant.guide.base.BaseActivity;
import com.sitanyun.merchant.guide.base.ToastUtil;
import com.sitanyun.merchant.guide.base.XFragment;
import com.sitanyun.merchant.guide.bean.DeleteBean;
import com.sitanyun.merchant.guide.bean.ForgetsmscoedeBean;
import com.sitanyun.merchant.guide.bean.MessagesBean;
import com.sitanyun.merchant.guide.bean.UserInfo;
import com.sitanyun.merchant.guide.bean.UserVrBean;
import com.sitanyun.merchant.guide.bean.VersionBean;
import com.sitanyun.merchant.guide.callback.StringCallbacks;
import com.sitanyun.merchant.guide.frament.HomeFragment;
import com.sitanyun.merchant.guide.frament.ScenMyFragment;
import com.sitanyun.merchant.guide.frament.view.fragment.AnalysisFragment;
import com.sitanyun.merchant.guide.frament.view.fragment.MyFragment;
import com.sitanyun.merchant.guide.frament.view.inter.IUpdateNameAView;
import com.sitanyun.merchant.guide.presenter.impl.MainAPresenterImpl;
import com.sitanyun.merchant.guide.presenter.inter.IMainAPresenter;
import com.sitanyun.merchant.guide.signature.GenerateTestUserSig;
import com.sitanyun.merchant.guide.url.Urls;
import com.sitanyun.merchant.guide.view.inter.IMainAView;
import com.sitanyun.merchant.guide.view.inter.IVrWebAView;
import com.sitanyun.merchant.guide.weiht.Common;
import com.sitanyun.merchant.guide.weiht.DateUtils;
import com.sitanyun.merchant.guide.weiht.DeviceUuidFactory;
import com.sitanyun.merchant.guide.weiht.NotificationsUtils;
import com.sitanyun.merchant.guide.weiht.PermissionsUtils;
import com.sitanyun.merchant.guide.weiht.SPutils;
import com.sitanyun.merchant.guide.weiht.SharedPreferenceUtil;
import com.tencent.imsdk.v2.V2TIMAdvancedMsgListener;
import com.tencent.imsdk.v2.V2TIMCallback;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMSendCallback;
import com.tencent.qcloud.tuicore.TUIConstants;
import com.tencent.qcloud.tuicore.TUICore;
import com.tencent.qcloud.tuicore.TUILogin;
import com.tencent.qcloud.tuikit.tuicontact.bean.ContactItemBean;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import androidx.annotation.NonNull;
import androidx.core.app.NotificationChannelCompat;
import androidx.core.app.NotificationManagerCompat;
import androidx.fragment.app.FragmentTransaction;
import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.MediaType;

/**
 * 首页
 */

public class MainActivity extends BaseActivity implements IMainAView {


    @BindView(R.id.home_frament)
    FrameLayout homeFrament;
    @BindView(R.id.ll_main_home)
    LinearLayout llMainHome;
    @BindView(R.id.ll_main_members)
    LinearLayout llMainMembers;
    @BindView(R.id.ll_main_my)
    LinearLayout llMainMy;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;
    @BindView(R.id.im_home)
    ImageView imHome;
    @BindView(R.id.tv_home)
    TextView tvHome;
    @BindView(R.id.im_user)
    ImageView imUser;
    @BindView(R.id.tv_user)
    TextView tvUser;
    @BindView(R.id.im_my)
    ImageView imMy;
    @BindView(R.id.tv_my)
    TextView tvMy;
    @BindView(R.id.ll_main_analysis)
    LinearLayout llMainAnalysis;
    @BindView(R.id.im_analysis)
    ImageView imAnalysis;
    @BindView(R.id.tv_analysis)
    TextView tvAnalysis;
    private XFragment[] mFragments;
    private IMainAPresenter mIMainAPresenter;
    private static final String TAG = "jia";
    private UserVrBean.CloudCustomDataBean cloudCustomDataBean = new UserVrBean.CloudCustomDataBean();
    private ProgressDialog pd;
    private static final int REQUEST_STATE_CODE = 1010;
    private MessagesBean messagesBean;
    private String type ="2";
   //弹窗权限
    private void initpomision() {

        if (NotificationManagerCompat.from(MainActivity.this).areNotificationsEnabled()){
            LogUtils.i(TAG, "--> showPromptDialog -- 通知权限 已开启 = ");
        }else {
            LogUtils.i(TAG, "--> showPromptDialog -- 通知权限 未开启 = ");
            initdialog();
        }
    }
   //通知权限未开启
    private void initdialog() {
     // ToastUtil.showToast(MainActivity.this,"未开启通知权限");
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(MainActivity.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(MainActivity.this, R.layout.loginoutdialog_item, null);
        dialog.setContentView(view);
        dialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
       TextView ts_message=  view.findViewById(R.id.ts_message) ;
        TextView define= view.findViewById(R.id.define);
        define.setText("去设置");
       ts_message.setText("为了保证最佳体验，确保正常接收通知，请您打开通知和悬浮窗权限。");
       view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        define.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent localIntent = new Intent();
                localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                if (Build.VERSION.SDK_INT >= 9) {
                    localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                    localIntent.setData(Uri.fromParts("package", getApplicationContext().getPackageName(), null));
                } else if (Build.VERSION.SDK_INT <= 8) {
                    localIntent.setAction(Intent.ACTION_VIEW);
                    localIntent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    localIntent.putExtra("com.android.settings.ApplicationPkgName", "");
                }
                startActivity(localIntent);
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);
    }


    //收到极光推送
    private void initgetintent() {
        if (!getIntent().getStringExtra("cid").equals("null")) {
                MessagesBean testBean=  new Gson().fromJson(getIntent().getStringExtra("cid"), MessagesBean.class);
                if (testBean.getBehavior().equals("MEETING")) {
                    type="1";
                        startActivity(new Intent(MainActivity.this, VrWebActivity.class)
                                .putExtra("urlss", testBean.getVrsrc() + "")
                                .putExtra("names", testBean.getSceneName() + "")
                                .putExtra("scenid", testBean.getSceneId() + "")
                                .putExtra("storeid", testBean.getStoreId() + "")
                                .putExtra("shops", testBean.getStoreName() + "")
                                .putExtra("starfname", testBean.getStaffName() + "")
                                .putExtra("cids", testBean.getCId() + "")
                                .putExtra("headurl", testBean.getHeadUrl() + "")
                                .putExtra("headname", testBean.getCName() + "")
                                .putExtra("cphone", testBean.getCPhone() + "")
                                .putExtra("type", "2"));

                } else if (testBean.getBehavior().equals("MESSAGE")) {
                    initcallread(testBean.getNoticeId()+"");

                    Bundle bundles = new Bundle();
                    bundles.putString(TUIConstants.TUIChat.CHAT_ID, "cid_" + testBean.getCId());
                    bundles.putString(TUIConstants.TUIChat.CHAT_NAME, testBean.getCName());
                    bundles.putInt(TUIConstants.TUIChat.CHAT_TYPE, ContactItemBean.TYPE_C2C);
                    TUICore.startActivity(TUIConstants.TUIChat.C2C_CHAT_ACTIVITY_NAME, bundles);
                } else if (testBean.getBehavior().equals("BROWSE")) {
                    startActivity(new Intent(MainActivity.this, VrWebActivity.class)
                            .putExtra("urlss", testBean.getVrsrc() + "")
                            .putExtra("names", testBean.getSceneName() + "")
                            .putExtra("scenid", testBean.getSceneId() + "")
                            .putExtra("storeid", testBean.getStoreId() + "")
                            .putExtra("shops", testBean.getStoreName() + "")
                            .putExtra("starfname", testBean.getStaffName() + "")
                            .putExtra("cids", testBean.getCId() + "")
                            .putExtra("headurl", testBean.getHeadUrl() + "")
                            .putExtra("headname", testBean.getCName() + "")
                            .putExtra("cphone", testBean.getCPhone() + "")
                            .putExtra("type", "2"));
                }

        } else {
          // ToastUtil.showToast(MainActivity.this, "第一次是正常进入首页，其他传递参数为空");

        }
    }

    /**
     *
     * @param s
     */
    private void initcallread( String s) {
        Map<String, List> hashMap = new HashMap<>();
        List lists = new ArrayList<>();
        lists.add(s);
        hashMap.put("list", lists);
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer " + SharedPreferenceUtil.getStringData("token"))
                .url(Urls.setIsRead)
                .content(new Gson().toJson(hashMap))
                .build().execute(new StringCallbacks() {
            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(String response, int id) {
                ForgetsmscoedeBean baseEntity = new Gson().fromJson(response, ForgetsmscoedeBean.class);
                if (baseEntity.getCode() == 0) {

                }
            }
        });
    }

    //广播
    private void initgb() {
        String reginid = JPushInterface.getRegistrationID(MainActivity.this);
        String id = DeviceUuidFactory.getIMEI(MainActivity.this);
       // Log.e("TAGS", reginid + "!!!!!" + id);
        //设置别名
        JPushInterface.setAlias(mActivity, 0, reginid);

        mIMainAPresenter.getsave(SharedPreferenceUtil.getStringData("staffid"), id, reginid, "Android");

    }

    //版本更新
    private void initversion() {
         mIMainAPresenter.getversion("ANDROID","GUIDE");

    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        mIMainAPresenter = new MainAPresenterImpl(this);
        initversion();
        initpomision();
        initgb();
        initgetintent();
        HomeFragment homeFragment = new HomeFragment();
        ScenMyFragment myusersFrament = new ScenMyFragment();
        AnalysisFragment analysisFragment = new AnalysisFragment();
        MyFragment myFragment = new MyFragment();
        mFragments = new XFragment[]{homeFragment, myusersFrament, analysisFragment, myFragment};
        getSupportFragmentManager().beginTransaction().add(R.id.home_frament, homeFragment)
                //.add(R.id.home_frament, myusersFrament).add(R.id.home_frament, analysisFragment).hide(myusersFrament).hide(analysisFragment)
                .show(homeFragment)
                .commit();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    public void initView() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            new PermissionsUtils(MainActivity.this).requestPermissions(new String[]{
                    Manifest.permission.RECORD_AUDIO,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE}, 100);

        }

        // 获取userSig函数
        // Log.e("TAG",SharedPreferenceUtil.getStringData("staffid"));
        String userSig = GenerateTestUserSig.genTestUserSig("staffid_" + SharedPreferenceUtil.getStringData("staffid"));
        TUILogin.login("staffid_" + SharedPreferenceUtil.getStringData("staffid"), userSig, new V2TIMCallback() {
            @Override
            public void onError(final int code, final String desc) {
            }

            @Override
            public void onSuccess() {
                // ToastUtil.showToast(MainActivity.this,"腾讯云注册成功");
                UserInfo.getInstance().setAutoLogin(true);
            }

        });

        /**
         * 接收消息
         */

        V2TIMManager.getMessageManager().addAdvancedMsgListener(new V2TIMAdvancedMsgListener() {
            @Override
            public void onRecvNewMessage(V2TIMMessage msg) {
                super.onRecvNewMessage(msg);
                int elemType = msg.getElemType();
                //同屏
                if (elemType == V2TIMMessage.V2TIM_ELEM_TYPE_CUSTOM) {
                    // 自定义消息
                    String cloudCustomData = msg.getCloudCustomData();
                    if (!cloudCustomData.isEmpty()) {
                        messagesBean = new Gson().fromJson(cloudCustomData, MessagesBean.class);
                        SimpleDateFormat fmtrq = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
                        Date now = new Date();
                        String value = messagesBean.getStartTime();
                        Date robottime = null;
                        try {
                            robottime = fmtrq.parse(value);
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        if (now.getTime() - robottime.getTime() >= 20000) {//1000表示1秒
                            System.out.println("超过20秒");

                        } else {
                            System.out.println("没有超过20秒");
                            //同屏讲解
                            Log.e("messagesBean", messagesBean.getBehavior() + "");
                            if (messagesBean.getBehavior().equals("MEETING_INVITE")) {
                                if (type.equals("1")) {
                                    getTopApp(MainActivity.this);
                                    type="2";
                                    return;
                                }else {
                                    //---------activity弹窗
                                    startActivity(new Intent(MainActivity.this, DialogActivity.class)
                                            .putExtra("beans", messagesBean).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                                    Log.e("TAGSSS", messagesBean.toString());
                                }

                                //浏览
                            } else if (messagesBean.getBehavior().equals("BROWSE")) {
//                         //当前时间
//                         SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
//                         Date date = new Date(System.currentTimeMillis());
//                         cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
//                                 "STAFF_CARD", cloudCustomDataBean = new UserVrBean
//                                 SharedPreferenceUtil.getStringData("nodeid")
//                                 , messagesBean.getSceneId()
//                                 , messagesBean.getSceneName()
//                                 , messagesBean.getStoreId()
//                                 , messagesBean.getStoreName()
//                                 , SharedPreferenceUtil.getStringData("staffid")
//                                 , SharedPreferenceUtil.getStringData("staffname")
//                                 , messagesBean.getCId(),
//                                 messagesBean.getCName(),
//                                 messagesBean.getCPhone(),
//                                 "0", simpleDateFormat.format(date));
//                         V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage(userSig.getBytes());
//                         // 发送消息
//                         String msgs = JSON.toJSONString(cloudCustomDataBean);
//                         v2TIMMessage.setCloudCustomData(msgs);
//                         V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_"+messagesBean.getCId(), null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
//                             @Override
//                             public void onError(int code, String desc) {
//                                 Log.e("TAG",code+""+desc);
//                             }
//
//                             @Override
//                             public void onSuccess(V2TIMMessage v2TIMMessage) {
//                                 Log.e("TAG","onSuccess");
//                             }
//
//                             @Override
//                             public void onProgress(int progress) {
//                                 Log.e("TAG","progress");
//                             }
//                         });
                                //回电
                            } else if (messagesBean.getBehavior().equals("CALL")) {
                                EventBus.getDefault().post("1");
                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss
                                Date date = new Date(System.currentTimeMillis());

                                cloudCustomDataBean = new UserVrBean.CloudCustomDataBean(
                                        "CALL_RECEIVE",
                                        SharedPreferenceUtil.getStringData("tonodeid")
                                        , messagesBean.getSceneId()
                                        , messagesBean.getSceneName()
                                        , messagesBean.getStoreId()
                                        , messagesBean.getStoreName()
                                        , SharedPreferenceUtil.getStringData("staffid")
                                        , SharedPreferenceUtil.getStringData("staffname")
                                        , messagesBean.getCId(),
                                        messagesBean.getCName(),
                                        messagesBean.getCPhone(),
                                        "0", simpleDateFormat.format(date));

                                V2TIMMessage v2TIMMessage = V2TIMManager.getMessageManager().createCustomMessage(userSig.getBytes());
                                // 发送消息
                                String msgs = JSON.toJSONString(cloudCustomDataBean);
                                v2TIMMessage.setCloudCustomData(msgs);
                                V2TIMManager.getMessageManager().sendMessage(v2TIMMessage, "cid_" + messagesBean.getCId(), null, V2TIMMessage.V2TIM_PRIORITY_DEFAULT, false, null, new V2TIMSendCallback<V2TIMMessage>() {
                                    @Override
                                    public void onError(int code, String desc) {
                                        Log.e("TAG", code + "" + desc);
                                    }

                                    @Override
                                    public void onSuccess(V2TIMMessage v2TIMMessage) {
                                        Log.e("TAG", "onSuccess");
                                    }

                                    @Override
                                    public void onProgress(int progress) {
                                        Log.e("TAG", "progress");
                                    }
                                });

                            } else if (messagesBean.getBehavior().equals("MEETING_REJECT")) {
                                getTopApp(MainActivity.this);
                                EventBus.getDefault().post("end");
                            } else if (messagesBean.getBehavior().equals("MEETING_END")) {
                                if (SPutils.getStringData("meetingstars").equals(messagesBean.getCId())) {
                                    // SPutils.SaveData("meetingstar", "meeting_end");
                                    SPutils.clearAll();
                                    EventBus.getDefault().post("end");
                                }
                                getTopApp(MainActivity.this);
                            } else if (messagesBean.getBehavior().equals("BROWSE_END")) {
                                if (SPutils.getStringData("meetingstars").equals(messagesBean.getCId())) {
                                    // SPutils.SaveData("meetingstar", "meeting_end");
                                    SPutils.clearAll();
                                    EventBus.getDefault().post("end");
                                }
                                getTopApp(MainActivity.this);
                            }
                            //留言
                            else if (messagesBean.getBehavior().equals("MESSAGE")) {
                                EventBus.getDefault().post("1");
                            }
                        }

                    }

                }

            }
        });
    }

    //判断弹窗是否在栈顶
    @SuppressLint("NewApi")
    private boolean getTopApp(Context mContext) {
        String lockAppName = "com.sitanyun.merchant.guide.view.activity.DialogActivity";
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        if (lockAppName.equals(topActivityName)) {
            DialogActivity.test_a.finish();
            return true;
        } else {

        }
        return false;
    }
    //判断弹窗是否在栈顶
    @SuppressLint("NewApi")
    private boolean getTopdialog(Context mContext) {
        String lockAppName = "com.sitanyun.merchant.guide.view.activity.DialogActivity";
        String topActivityName = "";
        ActivityManager am = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> runningTasks = am
                .getRunningTasks(1);
        if (runningTasks != null && !runningTasks.isEmpty()) {
            ActivityManager.RunningTaskInfo taskInfo = runningTasks.get(0);
            topActivityName = taskInfo.topActivity.getClassName();
        }
        if (lockAppName.equals(topActivityName)) {
           // DialogActivity.test_a.finish();

            return true;
        } else {

        }
        return false;
    }
    /**
     * 从dp单位转换为px
     *
     * @param dp dp值
     * @return 返回转换后的px值
     */
    private int dp2px(int dp) {
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    @Override
    public <T> T request(int requestFlag) {
        return null;
    }

    /**
     * 版本更新返回数据
     *
     * @param response
     * @param responseFlag
     * @param <T>
     */
    @Override
    public <T> void response(T response, int responseFlag) {
        if (responseFlag == IVrWebAView.RESPONSE_ONE) {
            VersionBean versionBean = (VersionBean) response;
            Log.e("TA", response.toString());
            //获取版本号
            String versions = Common.getVersion(MainActivity.this);
            String getversions = versionBean.getData().getVersion();
            if (Common.compareVersion(versions, getversions) == -1) {

                //1、使用Dialog、设置style
                final Dialog dialogs = new Dialog(MainActivity.this, R.style.DialogTheme);
                //2、设置布局
                View view = View.inflate(MainActivity.this, R.layout.version_item, null);
                TextView conent = view.findViewById(R.id.tv_vscont);
                TextView vsmsg = view.findViewById(R.id.tv_vsmsg);
                conent.setText(versionBean.getData().getComment());
                vsmsg.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        // 设置提示界面
                        if (DateUtils.isFastClick()) {
                            return;
                        }
                        startActivity(new Intent(MainActivity.this, AgreementActivity.class).putExtra("weburl", "4"));
                    }
                });
                dialogs.setContentView(view);
                dialogs.setCanceledOnTouchOutside(false);
                dialogs.setCancelable(false);
                //取消
                if (versionBean.getData().isForced() == false) {
                    view.findViewById(R.id.no_vs).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialogs.dismiss();
                        }
                    });
                } else {
                    view.findViewById(R.id.no_vs).setVisibility(View.GONE);
                }

                //确定
                view.findViewById(R.id.yes_vs).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                         if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                                 != PackageManager.PERMISSION_GRANTED) {
//                             // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
//                             ActivityCompat.requestPermissions(MainActivity.this, new String[]{
//                                     Manifest.permission.WRITE_EXTERNAL_STORAGE
//                             }, REQUEST_STATE_CODE);
//                         }

                        dialogs.dismiss();
                        pd = new ProgressDialog(MainActivity.this);
                        pd.setCancelable(false);
                        pd.show();

                        downloadFile(MainActivity.this, versionBean.getData().getUrl());
////                        //第二种
                        //               DownLoadApk.download(MainActivity.this, versionBean.getData().getUrl(), versionBean.getData().getComment(), versionBean.getData().getAppName());
                        //第三种
                        //      AppInnerDownLoder.downLoadApk(MainActivity.this,versionBean.getData().getUrl(),versionBean.getData().getAppName());


                    }
                });


                Window window = dialogs.getWindow();
                //设置弹出位置
                window.setGravity(Gravity.CENTER);
                //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                //设置弹出动画
                //   window.setWindowAnimations(R.style.main_menu_animStyle);
                //设置对话框大小
                window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                dialogs.show();
                /*添加View到当前显示的Activity*/
                //   MerchantApp.getInstance().showView(view);
            }
        }
    }

    //推送消息
    @Override
    public <T> void responsesave(T response, int responseFlag) {
        if (responseFlag == IUpdateNameAView.RESPONSE_ONE) {
            DeleteBean myUserInfoBean = (DeleteBean) response;
            if (myUserInfoBean.getCode() == 0) {

            } else {
                ToastUtil.showToast(MainActivity.this, myUserInfoBean.getMsg() + "");
            }
        }

    }
    //打开文件

    /**
     * @param context 上下文
     * @param fileUrl 下载完整url
     *                （我们从服务器端获取到的数据都是相对的地址）例如： "filepath": "/movie/20180511/1526028508.txt"
     */
    public void downloadFile(Context context, String fileUrl) {
        OkGo.<File>get(fileUrl).tag(context).execute(new FileCallback(
                context.getExternalFilesDir(null).getPath(), "vr.apk") { //文件下载时指定下载的路径以及下载的文件的名称
            @Override
            public void onStart(Request<File, ? extends Request> request) {
                super.onStart(request);
                Log.e("VERSION", "开始下载文件");
                //       ToastUtil.showToast(MainActivity.this,"开始下载文件");

            }

            @Override
            public void onSuccess(Response<File> response) {
                //       ToastUtil.showToast(MainActivity.this,"下载文件成功");
                Log.e("VERSION", "下载文件成功");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                //         ToastUtil.showToast(MainActivity.this,"下载文件完成");
                Log.e("VERSION", "下载文件完成");
                pd.setMessage("下载完成，请安装");
                openFile(MainActivity.this, new File(context.getExternalFilesDir(null).getPath() + "/vr.apk"));
                finish();


//                SPUtils.getInstance().put("localPath",mBasePath);
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                //    ToastUtil.showToast(MainActivity.this,"下载文件出错"+response.toString());
                Log.e("VERSION", "下载文件出错" + response.toString());

            }

            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                int dLProgress = (int) (progress.fraction * 100);
                pd.setTitle("正在下载");
                Log.e("VERSION", "正在下载");
                pd.setMessage("下载进度" + dLProgress + "%");
                LogUtils.e("文件下载的进度" + "DDDDD" + dLProgress);
            }
        });
    }

    /**
     * 打开文件
     *
     * @param context
     * @param f
     */
    private void openFile(Context context, File f) {
        Intent myIntent = new Intent(Intent.ACTION_VIEW);
//        myIntent.setAction("android.intent.action.VIEW");
//        String extension = android.webkit.MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(f).toString());
//        String mimetype = android.webkit.MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        Uri uri = null;
        if (Build.VERSION.SDK_INT >= 24) {
            StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
            StrictMode.setVmPolicy(builder.build());
            myIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            uri = Uri.fromFile(f);
            //    myIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        } else {
            uri = Uri.fromFile(f);
        }

        myIntent.setDataAndType(uri, "application/vnd.android.package-archive");
        myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(myIntent);

    }


    private int index;
    private int currentTabIndex;

    @OnClick({R.id.ll_main_home, R.id.ll_main_members,R.id.ll_main_analysis, R.id.ll_main_my})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_main_home:
                index = 0;
                imHome.setBackgroundResource(R.mipmap.home_xuan);
                tvHome.setTextColor(getResources().getColor(R.color.biue));
                imUser.setBackgroundResource(R.mipmap.msgw);
                tvUser.setTextColor(getResources().getColor(R.color.color_text_color));
                imAnalysis.setBackgroundResource(R.mipmap.home_sjyc);
                tvAnalysis.setTextColor(getResources().getColor(R.color.color_text_color));
                imMy.setBackgroundResource(R.mipmap.my_wei);
                tvMy.setTextColor(getResources().getColor(R.color.color_text_color));
                break;
            case R.id.ll_main_members:
                index = 1;
                imHome.setBackgroundResource(R.mipmap.home_wei);
                tvHome.setTextColor(getResources().getColor(R.color.color_text_color));
                imUser.setBackgroundResource(R.mipmap.msgx);
                tvUser.setTextColor(getResources().getColor(R.color.biue));
                imAnalysis.setBackgroundResource(R.mipmap.home_sjyc);
                tvAnalysis.setTextColor(getResources().getColor(R.color.color_text_color));
                imMy.setBackgroundResource(R.mipmap.my_wei);
                tvMy.setTextColor(getResources().getColor(R.color.color_text_color));
                break;
            case R.id.ll_main_analysis:
                index = 2;
                imHome.setBackgroundResource(R.mipmap.home_wei);
                tvHome.setTextColor(getResources().getColor(R.color.color_text_color));
                imUser.setBackgroundResource(R.mipmap.msgw);
                tvUser.setTextColor(getResources().getColor(R.color.color_text_color));
                imAnalysis.setBackgroundResource(R.mipmap.home_sjx);
                tvAnalysis.setTextColor(getResources().getColor(R.color.biue));
                imMy.setBackgroundResource(R.mipmap.my_wei);
                tvMy.setTextColor(getResources().getColor(R.color.color_text_color));
                break;
            case R.id.ll_main_my:
                index = 3;
                imHome.setBackgroundResource(R.mipmap.home_wei);
                tvHome.setTextColor(getResources().getColor(R.color.color_text_color));
                imUser.setBackgroundResource(R.mipmap.msgw);
                tvUser.setTextColor(getResources().getColor(R.color.color_text_color));
                imAnalysis.setBackgroundResource(R.mipmap.home_sjyc);
                tvAnalysis.setTextColor(getResources().getColor(R.color.color_text_color));
                imMy.setBackgroundResource(R.mipmap.my_xuan);
                tvMy.setTextColor(getResources().getColor(R.color.biue));
                break;
        }

        if (currentTabIndex != index) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(mFragments[currentTabIndex]);
            if (!mFragments[index].isAdded()) {
                trx.add(R.id.home_frament, mFragments[index]);
            }
            trx.show(mFragments[index]).commit();
        }
        currentTabIndex = index;

    }

    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                dialogout();
                // Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
//                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //物理返回
    private void dialogout() {
        //1、使用Dialog、设置style
        final Dialog dialog = new Dialog(MainActivity.this, R.style.DialogTheme);
        //2、设置布局
        View view = View.inflate(MainActivity.this, R.layout.loginoutdialog_item, null);
        dialog.setContentView(view);
        TextView tsmessage = (TextView) view.findViewById(R.id.ts_message);
        tsmessage.setText("确定关闭当前应用？");
        //取消
        view.findViewById(R.id.cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        //确定
        view.findViewById(R.id.define).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SPutils.clearAll();
                Intent home = new Intent(Intent.ACTION_MAIN);
                home.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                home.addCategory(Intent.CATEGORY_HOME);
                dialog.dismiss();
                startActivity(home);
            }
        });


        Window window = dialog.getWindow();
        //设置弹出位置
        window.setGravity(Gravity.CENTER);
        //  window.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        //设置弹出动画
        //   window.setWindowAnimations(R.style.main_menu_animStyle);
        //设置对话框大小
        window.setLayout(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        dialog.show();
        /*添加View到当前显示的Activity*/
        //   MerchantApp.getInstance().showView(view);

    }

    /**
     * 权限申请返回结果
     *
     * @param requestCode  请求码
     * @param permissions  权限数组
     * @param grantResults 申请结果数组，里面都是int类型的数
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {

            case REQUEST_STATE_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(this, "没有开启存储权限，保存失败!", Toast.LENGTH_LONG).show();
                    return;
                }
                break;
            case 100:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { //同意权限申请
                    //权限通过

                } else { //拒绝权限申请
                    //    PermissionUtil.gotoPermission(MainActivity.this);
                }
                break;

            default:
                break;
        }
    }


}
